import type { DesignStore } from '@/types'

const useDesignStore = defineStore('designStore', {
  state: (): DesignStore => ({
    primaryColor: '#409eff',
    theme: 'dark',
  }),
  getters: {
    isDark(state) {
      return state.theme === 'dark'
    },
  },
  actions: {
    switchTheme(theme?: DesignStore['theme']) {
      if (!theme) {
        theme = this.theme === 'dark' ? 'light' : 'dark'
      }
      const classList = document.documentElement.classList
      classList[theme === 'dark' ? 'add' : 'remove']?.(
        'dark',
      )
      this.theme = theme
    },
    setPrimaryColor(color: string | null) {
      if (!color)
        return
      color = rgbToHex(color)
      if (!color)
        return
      updateElementUITheme(color)
      this.primaryColor = color
    },
  },
  // ? 配置文档 https://prazdevs.github.io/pinia-plugin-persistedstate/zh/guide/config.html
  persist: {
    storage: localStorage,
    afterRestore: (ctx) => {
      // ctx.store.setPrimaryColor?.(
      //   ctx.store.$state.primaryColor
      // );
      const theme = ctx.store.$state.theme
      ctx.store.switchTheme(theme)
    },
  },
})

export default useDesignStore
